import re
from users.models import UserModel
from django.shortcuts import render
from rest_framework.views import APIView
# Create your views here.
from rest_framework.response import Response
from django.http.response import HttpResponse
# class CheckUserName(APIView):
#     def get(self,request,name):
#         if not name:
#             return Response({"msg":"效验失败"})


        # 校验用户名
class CheckUserName(APIView):
    def get(self,request,username):
        rule = r"^[a-zA-Z][a-zA-Z0-9]{5,15}$"
        res = re.findall(rule,username)
        if not res:
            return Response({
                "code":-1,
                "msg":"用户名必须以字母开头6-16位数字字母组合"
            })
        usercount = UserModel.objects.filter(username=username).count()
        if not usercount:
            return Response({
                "code":200,
                "msg":username
            })
        else:
            return Response({
                "code":-2,
                "msg":"该用户名以存在"
            })


        # 校验手机号
class CheckMobile(APIView):
    def get(self,request,mobile):
        if not mobile:
            Response({'msg':"手机号获取失败","code":400})
        try:
            user = UserModel.objects.get(mobile=mobile)
            return Response({"msg":"手机号已存在","code":400})
        except:
            return Response({"msg":"ok","code":200})

      # 生成图片验证码

import random
import string
import redis
from captcha.image import ImageCaptcha
class GenerateImgCode(APIView):
    def get(self,request,img_id):
        '''生成随机验证码'''
        code = "".join(random.sample(string.ascii_letters+string.digits,4))
        '''生成图片验证码'''
        img = ImageCaptcha()
        img_code = img.generate(code)
        print("生成的图片验证码是>>>",img_code)
        # 把生成图片的验证码，写入redis中
        rds = redis.Redis()
        # key是图片验证码的id，值是生成的随机数，有效期设置60s
        rds.setex("img_%s"%img_id,60,code)
        rds.close()
        return HttpResponse(img_code,content_type="image/png")

import redis
class CheckImageCode(APIView):
    def get(self,request):
        image_id = request.query_params.get("imageCodeID")
        image_code = request.query_params.get("imageCode")
        redis_cli = redis.Redis(host="localhost",port=6379)
        result = redis_cli.get('img_{}'.format(image_id))
        if result:
            if result.decode().lower() != image_code.lower():
                return Response({"msg":"验证码输入错误"})
            else:
                return Response({"code":200})
        else:
            return Response({"msg":"验证码已经过期"})


class UserRegister(APIView):
    def post(self,request):
        user_name = request.data.get("userName")
        pwd = request.data.get('pwd')
        mobile = request.data.get('mobile')
        agree = request.data.get('agree')

        if not all([user_name,pwd,mobile,agree]):
            return Response({"msg":"请输入完善注册用户信息","code":400})

        if not agree:
            return Response({"msg":"请勾选协议"})

        UserModel.objects.create_user(username=user_name,password=pwd,mobile=mobile)
        return Response({"msg":"注册成功","code":"201"})










